package servlet;

import bean.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@WebServlet(name = "testServlet", value = "/testServlet.s")
public class testServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String status = request.getParameter("status");
        final HttpSession session = request.getSession();
        final Object user = session.getAttribute("user");
        final String uuid = UUID.randomUUID().toString();
        final String s = uuid.toString();
        Result result = null;
        if ("true".equals(status)){
            final Cookie cookie = new Cookie(s, (String) user);
            cookie.setMaxAge(120);
            response.addCookie(cookie);
            result =new Result(1,"保存成功",cookie);
        }else if ("false".equals(status)){
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if ("user".equals(cookie.getName())) {
                        cookie= new Cookie(s, "");
                        cookie.setMaxAge(-1);
                        response.addCookie(cookie);
                        result =new Result(1,"关闭成功",cookie);
                    }
                }
            }
        }
        final String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
